package idv.arthur.work;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetMRBody
 */
//@WebServlet(description = "取得MR網站中的細項內容", urlPatterns = { "/GetMRBody" })
public class GetMRBody extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMRBody() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String xmlFileName = request.getParameter("fileName");
		URL url = new URL( "http://10.80.71.9:8000/or/mr/xml/"+xmlFileName);
		String resultQuery = "";
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		BufferedReader input = new BufferedReader( new InputStreamReader( (InputStream) connection.getContent() ) );
		Widgets wid = new Widgets();
		ArrayList<MRBody> mrBodys = new ArrayList<MRBody>();
		
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
			conn = wid.getConn(true);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse((InputStream) connection.getContent());
			doc.getDocumentElement().normalize();

			NodeList nodeLst = doc.getElementsByTagName("mr");

			String nodeContent = "Default status has content";
			String nodeName = "";
			Element ele = null;
			NodeList elmntLst = null;

			for (int s = 0; s < nodeLst.getLength(); s++) {

				MRBody mrBody = new MRBody();

				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					ele = (Element) fstNode;

					String mrid = fstNode.getAttributes().getNamedItem("id").getNodeValue();
					mrBody.setMrid(mrid);
					
					nodeName = "module";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else { 
						nodeContent = elmntLst.item(0).getTextContent();
						mrBody.setModule(nodeContent);
					}

					nodeName = "mrdescription";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						mrBody.setMrdescription(nodeContent);
					}
					
					nodeName = "tester";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							String[] tmp = nodeContent.split(" ");
							User[] userArray = null;
							if (tmp.length>0) {
								userArray = new User[tmp.length];
								for (int a=0;a<tmp.length;a++){
									userArray[a] = wid.checkUserId(tmp[a]);
								}	
							}
							mrBody.setTester(userArray);
						}
					}

					nodeName = "sourceid";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {

						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setSourceid(nodeContent);
						}
					}

					nodeName = "propose";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							int start = 0;
							int len = nodeContent.length() / 3;
							String[] propose = new String[len];
							for (int i = 0; i < len; i++) {
								propose[i] = nodeContent.substring(start,
										start + 3);
								start = start + 3;
							} 
							
							String[] tmp = propose;
							User[] userArray = null;
							if (tmp.length>0) {
								userArray = new User[tmp.length];
								for (int a=0;a<tmp.length;a++){
									userArray[a] = wid.checkUserId(tmp[a]);
								}	
							}
							mrBody.setPropose(userArray);
						}
					}
					
					
					nodeName = "isMail";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setIsMail(nodeContent);
						}
					}
					
					nodeName = "onlinedate";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setOnlinedate(nodeContent);
						}
					}
					
					nodeName = "createdate";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setCreatedate(nodeContent);
						}
					}

					nodeName = "mrno";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setMrno(nodeContent);
						}
					}

					nodeName = "process";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setProcess(nodeContent);
						}
					}

					nodeName = "yymm";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setYymm(nodeContent);
						}
					}

					nodeName = "desc";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							mrBody.setDesc(nodeContent);
						}
					}

					nodeName = "designpm";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							User[] userArray = new User[1];;
							userArray[0] = wid.checkUserId(nodeContent);
							mrBody.setDesignpm(userArray);
						}
					}

					
					nodeName = "designer";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						nodeContent = elmntLst.item(0).getTextContent();
						if (nodeContent.equalsIgnoreCase("")) {
						} else {
							int start = 0;
							int len = nodeContent.length() / 3;
							String[] designer = new String[len];
							for (int i = 0; i < len; i++) {
								designer[i] = nodeContent.substring(start,
										start + 3);
								start = start + 3;
							}
							
							String[] tmp = designer;
							User[] userArray = null;
							if (tmp.length>0) {
								userArray = new User[tmp.length];
								for (int a=0;a<tmp.length;a++){
									userArray[a] = wid.checkUserId(tmp[a]);
								}	
							}
							mrBody.setDesigner(userArray);
						}
					}
					
					nodeName = "programmer";
					elmntLst = ele.getElementsByTagName(nodeName);
					if (elmntLst.item(0) == null) {
					} else {
						Programmer programmers[] = new Programmer[elmntLst.getLength()];
						for (int i=0;i<elmntLst.getLength();i++) {
							Programmer programmer = new Programmer();
							programmer.setName(elmntLst.item(i).getAttributes().getNamedItem("name").getNodeValue());
							Element element = (Element) elmntLst.item(i);
							programmer.setContent(element.getElementsByTagName("content").item(0).getTextContent());
							programmers[i] = programmer;
						}
						mrBody.setProgrammer(programmers);
					}

					nodeName = "reference";
					int size_ref = ele.getElementsByTagName(nodeName).getLength();
					elmntLst = ele.getElementsByTagName(nodeName);
					if (size_ref == 0) {
					} else {
						String[] reference = new String[size_ref];
						for (int i=0;i<size_ref;i++){
							nodeContent = elmntLst.item(i).getTextContent();
							if (nodeContent.equalsIgnoreCase("")) {
							} else {
								reference[i] = nodeContent;
								mrBody.setReference(reference);
							}							
						}
					}
					Require[] requeireLog = null; 
					mrBody.setRequire(requeireLog);
					
					mrBodys.add(mrBody);
				}
			}
		} catch (Exception e) {
			wid.keepErrorMes(conn, ps, e,"", true);
		} finally {
			try {
				if (ps!= null) { ps.close(); }
				if (conn != null) { conn.close(); }	
			} catch (SQLException  e) {}
		}
		input.close();
		resultQuery = new Gson().toJson(mrBodys);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(resultQuery);
	}
}